import {
  _decorator,
  Component,
  EventTouch,
  Input,
  input,
  instantiate,
  Node,
  UITransform,
  Vec2,
} from "cc";
import DataManager from "../../Global/DataManager";
import { EntityTypeEnum, IActor, InputTypeEnum } from "../../Common";
import { EntityManager } from "../../Base/EntityManager";
import { EntityStateEnum, EventEnum } from "../../Enum";
import { WeaponStateMachine } from "./WeaponStateMachine";
import EventManager from "../../Global/EventManager";
const { ccclass, property } = _decorator;

@ccclass("WeaponManager")
export class WeaponManager extends EntityManager {
  owner: number;
  private body: Node;
  private anchor: Node;
  private point: Node;
  init(data: IActor) {
    this.owner = data.id;
    this.body = this.node.getChildByName("Body");
    this.anchor = this.body.getChildByName("Anchor");
    this.point = this.anchor.getChildByName("Point");
    this.fsm = this.body.addComponent(WeaponStateMachine);
    this.fsm.init(data.weaponType);
    this.state = EntityStateEnum.Idle;
    EventManager.Instance.on(
      EventEnum.WeaponShoot,
      this.handleWeaponShoot,
      this
    );
  }
  onDestroy() {
    EventManager.Instance.off(
      EventEnum.WeaponShoot,
      this.handleWeaponShoot,
      this
    );
  }
  handleWeaponShoot() {
    // 点的世界坐标
    const pointWorldPos = this.point.getWorldPosition();
    // 上面的转舞台坐标
    const pointStagePos = DataManager.Instance.stage
      .getComponent(UITransform)
      .convertToNodeSpaceAR(pointWorldPos);
    // 锚的世界坐标
    const anchorWorldPos = this.anchor.getWorldPosition();
    // 算出方向的向量,不加normalize()（归一化）是50，反之为1，因为方向没有长度，只有 1 or -1
    const direction = new Vec2(
      pointWorldPos.x - anchorWorldPos.x,
      pointWorldPos.y - anchorWorldPos.y
    ).normalize();
    DataManager.Instance.applyInput({
      type: InputTypeEnum.WeaponShoot,
      owner: this.owner,
      position: {
        x: pointStagePos.x,
        y: pointStagePos.y,
      },
      direction: {
        x: direction.x,
        y: direction.y,
      },
    });
  }
}
